const path = require('path')
const fs = require('fs-extra')
const { allProductVersions } = require('./src/utils/version_config')

const config = {
  versions: Object.keys(allProductVersions.mogdb.versions), // 所有mogdb版本
  langArr: ['zh', 'en'] // 目前支持的语言
}

run()

function run () {
  const allParams = {}
  const { versions, langArr } = config
  langArr.forEach(lang => {
    allParams[lang] = {}
    versions.forEach(version => {
      const directory = path.join(process.cwd(), `product/${lang}/docs-mogdb/${version}`) // 参数存放文件夹
      allParams[lang][version] = getVersionParams(directory)
    })
  })
  // 在public下创建params.js
  fs.writeFileSync(`public/params.json`, JSON.stringify(allParams))
}

function getVersionParams (directory) {
  const params = {}
  
  // 根据文档总toc目录，获取全部参数文件名
  const tocPath = path.join(directory, 'toc.md')
  const tocContents = getFileContent(tocPath)
  if (!tocContents) return {}
  const paramsFilePath = []
  const items = tocContents.match(/\[(.*?)\]\((.*?)\)/g) // 查找合法目录项
  items.map(item => {
    let filePath = (item.match(/(\/.*\/guc-parameters\/.*\.md)\)/g) || [''])[0].replace(')', '') // 查找含有guc-parameters的目录
    if (filePath) paramsFilePath.push(filePath)
  })

  // 遍历参数文件，查找二级目录
  paramsFilePath.forEach(item => {
    const filename = item.match(/([^\/]+)\.md/g)[0].replace('.md', '') // 获取文件名称
    const filePath = path.join(directory, item)
    const fileContents = getFileContent(filePath)
    if (fileContents) {
      fileContents.replace(/##[ ]*(\w+)/g, (_, name) => {
        name = name.replace(/\s+/g, '')
        params[name] = `${filename}#${name.toLowerCase()}`
      })
    }
  })
  return params
}

function getFileContent (path) {
  if (fs.pathExistsSync(path)) {
    return fs.readFileSync(path, 'utf8')
  }
  return null
}